package com.rk.kbk.service;

import com.rk.kbk.common.FailException;
import com.rk.kbk.common.JsonCodeEnum;
import com.rk.kbk.common.JsonResp;
import com.rk.kbk.common.Md5;
import com.rk.kbk.dao.AdminAuthorityDao;
import com.rk.kbk.dao.AdminDao;
import com.rk.kbk.model.Admin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;

/**
 * @AdminService
 * @管理员Service
 * @version : Ver 1.0
 */
@Service
@Transactional
public class AdminService {
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private AdminAuthorityDao adminAuthorityDao;
    @Autowired
    private SessionDAO sessionDAO;

    /**
     * 获得当前用户id
     * @return
     */
    public Long currentUserId() {
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection collection = subject.getPrincipals();
        if (null != collection && !collection.isEmpty()) {
            String userName = (String) collection.iterator().next();
            return adminDao.findOneByUserName(userName).getId();
        }
        throw new FailException(JsonCodeEnum.OVERTIME.getMessage());
    }

    /**
     * 获取当前登陆用户
     * @return
     */
    public Admin currentUser() {
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection collection = subject.getPrincipals();
        if (null != collection && !collection.isEmpty()) {
            String userName = (String) collection.iterator().next();
            return adminDao.findOneByUserName(userName);
        }
        throw new FailException(JsonCodeEnum.OVERTIME.getMessage());
    }

    /**
     * 登录
     * @param userName 用户名
     * @param password 密码
     * @return JsonResp
     */
    public JsonResp login(String userName, String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, Md5.md5Encode(password));
        try {
            //踢除用户
            this.kickOutUser(token);
        }catch (Exception e) {
            String message = e.getMessage();
            if (!message.contains("There is no session with id [")) {
                e.printStackTrace();
            }
        }finally {
            this.kickOutUser(token);
        }
        try{
            subject.login(token);
            Session session = subject.getSession();
            Serializable sessionId = session.getId();
            System.out.println("sessionId:"+sessionId);
            System.out.println("sessionHost:"+session.getHost());
            System.out.println("sessionTimeout:"+session.getTimeout());
            System.out.println(userName+"登录成功");
            Admin admin = adminDao.findOneByUserName(userName);
            admin.setToken(sessionId.toString());
            return JsonResp.ok(admin);
        }catch(Exception e){
            throw new FailException("用户名或密码错误！");
        }

    }

    /**
     * 获取当前登陆用户
     * @return JsonResp
     */
    public JsonResp findLoginUser() {
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection collection = subject.getPrincipals();
        if (null != collection && !collection.isEmpty()) {
            String userName = (String) collection.iterator().next();
            return JsonResp.ok(adminDao.findOneByUserName(userName));
        }
        throw new FailException(JsonCodeEnum.OVERTIME.getMessage());
    }

    /**
     * 踢除用户
     * http://www.ithao123.cn/content-7174367.html
     */
    private void kickOutUser(UsernamePasswordToken token){
        String loginName = token.getUsername();
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for(Session session:sessions){
            if (session.getTimeout()==0) {
                sessionDAO.delete(session);
            }
            if(loginName.equals(String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)))) {
                //设置session立即失效，即将其踢出系统
                session.setTimeout(0);
                logout();
            }
        }
    }

    /**
     * 退出登录
     */
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            // session 会销毁，在SessionListener监听session销毁，清理权限缓存
            subject.logout();
        }
    }
}
